package org.qydjk.console.controller.basic;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.Area;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.Tree;
import org.qydjk.console.service.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/areaInfo")
public class AreaController extends BaseController {
    @Autowired
    private IAreaService areaService;

    /**
     * 跳转到区域页
     *
     * @return
     */
    @RequestMapping("/areaInfo.do")
    public String areaInfo() {
        return "basic/areaInfo/areaInfo";
    }

    /**
     * 初始化区域页面数据
     */
    @RequestMapping("/treeGrid.do")
    @ResponseBody
    public Object treeGrid(Integer page, Integer rows, String sort, String order) throws Exception {
        try {
            List<Area> areaList = baseService.findByHql("FROM Area a ORDER BY a.ord ");
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/addPage.do")
    public String addPage() {
        return "basic/areaInfo/areaInfoAdd";
    }

    /**
     * 查询所有的菜单
     */
    @RequestMapping("/allTree.do")
    @ResponseBody
    public Object allMenu() throws Exception {
        try {
            List<Tree> trees = new ArrayList<Tree>();
            // 查询所有菜单
            List<Area> areaLists = baseService.findByHql("from Area c order by c.id");
            if (areaLists == null) {
                return trees;
            }
            boolean needRoot = true;
            String root = request.getParameter("root");
            if(StringUtil.isEmptyOrNull(root)){
                needRoot = false;
            }
            return buildTree(areaLists,needRoot);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建树
     *
     * @param resourceLists
     * @return
     */
    private List<Tree> buildTree(List<Area> resourceLists,boolean needRoot) {
        try {
            List<Tree> trees = new ArrayList<Tree>();
            for (Area area : resourceLists) {
                Tree tree = new Tree();
                tree.setId(area.getId());
                if((area.getParentId() == null || area.getParentId().intValue() == 0) && needRoot){
                    tree.setPid(-1);
                }else{
                    tree.setPid(area.getParentId());
                }
                tree.setText(area.getName());
                trees.add(tree);
            }
            if(needRoot){
                Tree tree = new Tree();
                tree.setId(-1);
                tree.setPid(null);
                tree.setText("根节点");
                trees.add(tree);
            }
            return trees;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加资源
     *
     * @param area
     * @return
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object add(@Valid Area area) throws Exception {
        try {
            Date date = new Date();
            area.setCreateTime(date);
            area.setUpdateTime(date);
            updateLevel(area);
            //保存area并更新父节点为非叶子节点
            areaService.saveAreaAndUpdateParentLeaf(area);
            return renderSuccess("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改分类级别
     *
     * @param area
     * @throws Exception
     */
    public void updateLevel(Area area) throws Exception {
        try {
            Integer parentId = area.getParentId();
            if (parentId != null) {
                Area parentArea = baseService.findSingleByHql("FROM Area c WHERE c.id = " + parentId);
                if (parentArea != null) {
                    area.setLevel(parentArea.getLevel() + 1);
                }
            } else {
                area.setLevel(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑资源页
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage.do")
    public String editPage(Model model, Integer id) throws Exception {
        try {
            Area area = baseService.get(Area.class, id);
            model.addAttribute("area", area);
            return "basic/areaInfo/areaInfoEdit";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 编辑资源
     *
     * @param area
     * @return
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object edit(@Valid Area area, Integer oldParentId) throws Exception {
        try {
            Area ss = baseService.get(Area.class, area.getId());
            BeanUtil.copyProperties(area, ss);
            ss.setParentId(area.getParentId());
            ss.setUpdateTime(new Date());
            updateLevel(ss);
            areaService.updateAreaAndUpdateParentLeaf(ss, oldParentId);

            return renderSuccess("编辑成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除资源
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object delete(Integer id) throws Exception {
        try {
            Area area = new Area();
            area.setId(id);
            List<Area> areaList = baseService.findByHql("FROM Area c WHERE c.parentId = " + id);
            if (areaList != null && areaList.size() > 0) {
                return renderSuccess("当前分类存在子分类,请先删除子分类！");
            } else {
                areaService.deleteAreaAndUpdateParentLeaf(area);
                return renderSuccess("删除成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 区别获取省市区地址
     * author：Lanan 2017-12-14
     *
     * @param type 1:省 2：市 3：区
     * @param pid  所属ID parentID
     */
    @RequestMapping("/addressList.do")
    @ResponseBody
    public Object getAddressList(String type, Integer pid) {
        try {
            String hql = "from Area where level = " + type;
            if (pid != null) {
                hql += "and parentId = " + pid.intValue();
            }
            List<Area> areas = new ArrayList<Area>();
            try {
                areas = baseService.findByHql(hql);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return areas;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化区域页面数据
     */
    @RequestMapping("/cityTreeGrid.do")
    @ResponseBody
    public Object cityTreeGrid(Integer page, Integer rows, String sort, String order) throws Exception {
        try {
            List<Area> areaList = baseService.findByHql("FROM Area a WHERE a.level < 3 ORDER BY a.ord ");
            Area defaultArea = new Area();
            defaultArea.setId(0);
            defaultArea.setName("默认城市");
            defaultArea.setParentId(null);
            areaList.add(0,defaultArea);
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化区域页面数据
     */
    @RequestMapping("/selectCityTree.do")
    @ResponseBody
    public Object selectCityTree(Integer page, Integer rows, String sort, String order) throws Exception {
        try {
            List<Area> areaList = baseService.findByHql("FROM Area a WHERE a.level < 3 ORDER BY a.ord ");
            return buildTree(areaList,false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
